home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2158 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.2 KB

  1. Path: nnrp.info.ucla.edu!usenet
  2. From: bruin@ucla.edu (UCLA Bruin)
  3. Newsgroups: gnu.g++.help,comp.lang.c++
  4. Subject: Re: Operator Overloading - Result not Expected!
  5. Date: Tue, 16 Jan 1996 05:57:38 GMT
  6. Organization: Universal Exports
  7. Message-ID: <4dfemd$1lhs@saba.info.ucla.edu>
  8. References: <4dedk3$fo2@panix.com>
  9. Reply-To: bruin@ucla.edu
  10. NNTP-Posting-Host: s110_13.resnet.ucla.edu
  11. X-Newsreader: Forte Free Agent 1.0.82
  12.  
  13.  
  14. acinader@panix.com (Arthur Cinader) wrote:
  15.  
  16. >I am teaching myself to program with "How To Program C++" by
  17. >Deitel & Deitel.  A great book. 
  18.  
  19. Maybe...  But if their book is so great, why didn't their code work?
  20. =)  I recommend The C++ Primer Plus by Prata, but anyways...  I can
  21. explain the problem in their code.
  22.  
  23. >Using g++ v2.4 on BSDI I compile with:
  24. >g++ -o fig8.3 fig8.3.C
  25.  
  26. You can just type g++ fig8.3.cpp
  27.  
  28.  
  29. >// overloaded stream extraction operator
  30. >istream &operator>>(istream &input, PhoneNumber &num)
  31. >{
  32. >   input.ignore();                 // skip (
  33. >   input.getline(num.areaCode, 4); // input area code
  34. >   input.ignore(2);                // skip ) and space
  35. >   input.getline(num.exchange, 4); // input exchange
  36. >   input.ignore();                 // skip dash (-)
  37. >   input.getline(num.line, 5);     // input line
  38.  
  39. The problem lies here.  cin.getline is supposed to be used for reading
  40. all the characters on a line (spaces included) up until the newline
  41. and then ignoring the newline character.  As a sefety measure to
  42. ensure you don't fill your string beyond it's bounds, you can pass an
  43. optional integer to cin.getline to tell it when to stop the input.
  44. With g++, cin.getline skips over the remaining characters on the line
  45. until it reads in and ignores the newline.  However, with Borland C++,
  46. it leaves the remaining characters and newline intact.  In other
  47. words, the author probably was using Borland C++ and failed to test
  48. his program with g++ for UNIX.  The two versions have some
  49. differences..  =)  So basically with your C++ compiler it read the
  50. first four characters and then ignored the rest of the input, hence
  51. the result you were getting...
  52.  
  53. But all is not lost...  If you use cin.get instead of cin.getline this
  54. code will work perfectly under both compilers.  The author of your
  55. book used the wrong method for the wrong purpose.
  56.  
  57. Hope this help!
  58.  
  59.     Nate
  60.  
  61.